package com.xhtt.smart.card.client;

import com.alibaba.fastjson.JSON;
import com.xhtt.smart.card.client.init.NettyClientInit;
import com.xhtt.smart.card.common.msg.bean.MsgClientBean;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;

/**
 * @author wangze
 * @date 2018-07-04 14:23.
 **/
@Component
public class NettyClient {
    private final static Logger LOGGER = LoggerFactory.getLogger(NettyClient.class);

    private EventLoopGroup group = new NioEventLoopGroup();

    private Bootstrap bootstrap = new Bootstrap();

    @Value("${netty.server.port}")
    private int nettyPort;

    @Value("${netty.server.host}")
    private String host;

    private SocketChannel channel;


    @PostConstruct
    public void start() throws InterruptedException {
        bootstrap.group(group)
                .channel(NioSocketChannel.class)
                .handler(new NettyClientInit());

        ChannelFuture future = bootstrap.connect(host, nettyPort).sync();
        if (future.isSuccess()) {
            LOGGER.info("启动 Netty 成功");
        }
        channel = (SocketChannel) future.channel();
    }


    public void connect() {
        bootstrap.connect();
    }


    /**
     * 发送消息
     *
     * @param msg
     */
    public void sendMsg(MsgClientBean msg) {
        ChannelFuture future = channel.writeAndFlush(msg);
        future.addListener((ChannelFutureListener) channelFuture ->
                LOGGER.info("客户端手动发消息成功 {}", JSON.toJSONString(msg)));

    }
}
